# -*- coding:utf-8 -*-
"""
describe：配置文件
Author：tang
Email：tangllyx@163.com
Time: 2023/4/17
Software: PyCharm
"""
import os
from datetime import datetime, timedelta
from playwright.sync_api import Page, expect, Playwright
from Config.config import *
import json


class tool:

    def element_drag_and_drop(self,element, offset: dict):
        """
        元素拖动
        :param element: 定位元素
        :param offset: 移动距离
        :return:
        """
        # 获取滑块的位置
        element_position = element.bounding_box()
        # 按住滑块
        mouse = self.mouse
        mouse.move(element_position['x'], element_position['y'])
        mouse.down()
        # 拖动元素到指定位置
        mouse.move(element_position['x'] + offset.get('x'), element_position['y'] + offset.get('y'))
        # 释放鼠标
        mouse.up()

    def nowtime(YMD:str = None,Name:str = None,tomorrow:int = None):
        # 方法一：获取当前时间并格式化为指定字符串格式
        time = datetime.now()
        if tomorrow != None:
            time = time + timedelta(tomorrow)
        if YMD == "ymd":
            time = time.strftime("%Y-%m-%d")
            if Name != None:
                time = "AT" + time + "_" + Name
        else:
            time = time.strftime("%Y-%m-%d %H-%M-%S")
            if Name != None:
                time = "AT" + time + "_" + Name
        print(time)
        return time

    def api(self):
        # 3.解析接口获取审批人
        # 读取cookie JSON文件
        with open(cookie_dir + "cookie.json", 'r', encoding='utf-8') as f:
            data = json.load(f)
            print(data)

        # 寻找cookie位置
        cookieInLists = data["origins"][0]["localStorage"]
        cookieIndex = 10000
        for list in cookieInLists:
            if list["name"] == "pit_token":
                cookieIndex = cookieInLists.index(list)
                break
        if cookieIndex == 10000:
            print("！！！未提取到cookie数据！！！")
        # 提取cookie数据--给接口使用（这里只是打印出来）
        cookie = cookieInLists[cookieIndex]["value"]
        print(cookie)
        # cookie后缀带|String--删除掉
        webcookie = cookie.replace("|String", "")
        head = {
            # "Accept": "application/json, text/plain, */*",
            # Add GitHub personal access token.
            "Authorization": webcookie,
        }
        # context = playwright.request.new_context(base_url='http://172.18.3.26:7300')
        httpcontext = playwright.request.new_context()
        response = httpcontext.get(url=Base.geturl(), headers=head)
        responsejson = response.json()
        print("解析接口获取审批人:")
        print(responsejson)
        # while len(responsejson["data"]["runTask"]) != 0:
        while len(httpcontext.get(url=Base.geturl(), headers=head).json()["data"]["runTask"]) != 0:
            peoples = []
            peopleCount = httpcontext.get(url=Base.geturl(), headers=head).json()["data"]["runTask"]
            for person in peopleCount:
                peoples.append(person["handledDtoList"][0]["handledByName"])
            # people = responsejson["data"]["runTask"][0]["handledDtoList"][0]["handledByName"]
            node = httpcontext.get(url=Base.geturl(), headers=head).json()["data"]["runTask"][0]["signDeployDTO"][
                "signKeyword"]
            print("下节点审批人：" + f'{peoples}' + "   节点：" + node)
            # 4.审批人转换为账号
            approvalpeople = ''
            if "陈凯" in peoples:
                approvalpeople = "shigong1"
                print("审批使用账户： " + approvalpeople)
            elif "谭监" in peoples:
                approvalpeople = "jianli1"
                print("审批使用账户： " + approvalpeople)
            else:
                approvalpeople = "admin"
                print("审批使用账户： " + approvalpeople)

            if approvalpeople == '':
                approvalpeople = peoples[0]
                print("！！！审批人里没有找到配对人员，使用流程账号审批： " + approvalpeople)

    def starflow(page:Page,who:str=None):
        page.wait_for_timeout(2000)
        page.get_by_role("button", name="发起流程").click()
        if page.locator("xpath=//p[@class=\"el-message__content\"]").is_visible():
            expect(page.get_by_role("alert")).to_contain_text("流程发起成功")
        page.wait_for_timeout(500)
        if page.get_by_placeholder("请选择下一审批人").is_visible():
            page.get_by_placeholder("请选择下一审批人").click()
            if who:
                page.get_by_placeholder("请输入用户账号").fill(who)
                page.get_by_placeholder("请输入用户账号").press("Enter")
                page.wait_for_timeout(500)
                page.get_by_title(who).first.click()
            else:
                page.get_by_role("treeitem").first.click()
            page.get_by_role("button", name="确 定").click()
            page.get_by_role("button", name="确定").click()
            expect(page.get_by_role("alert")).to_contain_text("流程发起成功")
        if  page.get_by_placeholder("请输入签署密码").is_visible():
            page.get_by_placeholder("请输入签署密码").fill(password_flow)
            page.get_by_role("button", name="确定").click()
            expect(page.locator("body")).to_contain_text("操作成功")




